﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Furion.DatabaseAccessor;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using YShop.Application.Contracts.System.Routes;
using YShop.Core.Managers.Caches;
using YShop.Core.System;
using YShop.Core;

namespace YShop.Application.System
{
    /// <summary>
    /// 路由
    /// </summary>
    [ApiDescriptionSettings("System")]
    public class RouteService : CrudService<Route, RouteDto, RouteDto, PageSearchDto, RouteDto, RouteDto>,IBaseService
    {
        /// <summary>
        /// 仓储
        /// </summary>
        private readonly IRepository<Route> _repository;
        /// <summary>
        /// 缓存
        /// </summary>
        private readonly CacheManager _cacheManager;

        /// <summary>
        /// 全部路由数据
        /// </summary>
        public override List<Route> EntitiesCache => _cacheManager.GetOrCreate(CacheKeys.Routes, _ =>
        {
            return _repository.Include(s => s.Meta, false).ToList();
        });
        public override string EntitiesCacheKey => CacheKeys.Routes;

        public RouteService(IRepository<Route> repository,CacheManager cacheManager) : base(repository)
        {
            _repository = repository;
            _cacheManager = cacheManager;

        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="pageSearchDto"></param>
        /// <returns></returns>
        public override async Task<PagedList<RouteDto>> GetListAsync([FromQuery] PageSearchDto pageSearchDto)
        {
            return (await EntitiesCache.ToPageListAsync(pageSearchDto.PageIndex, pageSearchDto.PageSize)).Adapt<PagedList<RouteDto>>();
        }
        /// <summary>
        /// 获取权限路由
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public List<RouteHasChildrenDto> GetAccess(string token)
        {
            var results = new List<RouteHasChildrenDto> { EntitiesCache.First(s => s.Path == "/").Adapt<RouteHasChildrenDto>() };
            results.First().Children.AddRange(EntitiesCache.Where(s=>s.Path != "/").Adapt<List<RouteHasChildrenDto>>());
            return results;
        }
    }
}
